package com.barradata.common.view;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatEditText;

import com.barradata.R;
import com.jakewharton.rxbinding3.view.RxView;
import com.jakewharton.rxbinding3.widget.RxTextView;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;


/**
 * Created by WuNan on 15/11/23.
 */
public class EditTextCleanable extends AppCompatEditText {
    private Drawable mCleanTextDrawable;
    private Disposable showCleanerSubscription;

    Consumer<Boolean> focusAction;

    public void setAction(Consumer<Boolean> action) {
        this.focusAction = action;
    }

    public EditTextCleanable(Context context) {
        super(context);
        init(context, null);
    }

    public EditTextCleanable(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }


    private void init(Context context, AttributeSet attrs) {
        //获取图片资源
        mCleanTextDrawable = context.getResources().getDrawable(R.drawable.edit_text_cleanner);
        //文本变更事件
        Observable<Boolean> textChangeObservable = RxTextView.textChanges(this)
                .map(charSequence -> charSequence.length() > 0);
        //focus事件
        Observable<Boolean> focusChangesObservable = RxView.focusChanges(this).map(aBoolean -> {
            if (focusAction != null) {
                focusAction.accept(aBoolean);
            }
            return aBoolean;
        });
        //连接最近的两次事件
        showCleanerSubscription = Observable.combineLatest(
                textChangeObservable,
                focusChangesObservable,
                (aBoolean, aBoolean2) ->
                        aBoolean && aBoolean2)
                .subscribe(aBoolean -> {
                    //设置clear图标
                    setCompoundDrawablesWithIntrinsicBounds(null, null,
                            aBoolean ? mCleanTextDrawable : null, null);
                });
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mCleanTextDrawable != null && event.getAction() == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            //判断触摸点是否在水平范围内
            boolean isInnerWidth = (x > (getWidth() - getTotalPaddingRight())) &&
                    (x < (getWidth() - getPaddingRight()));
            //获取删除图标的边界，返回一个Rect对象
            Rect rect = mCleanTextDrawable.getBounds();
            //获取删除图标的高度
            int height = rect.height();
            int y = (int) event.getY();
            //计算图标底部到控件底部的距离
            int distance = (getHeight() - height) / 2;
            //判断触摸点是否在竖直范围内(可能会有点误差)
            //触摸点的纵坐标在distance到（distance+图标自身的高度）之内，则视为点中删除图标
            boolean isInnerHeight = (y > distance) && (y < (distance + height));

            if (isInnerWidth && isInnerHeight) {
                setText("");
            }

        }
        return super.onTouchEvent(event);
    }


    @Override

    protected void finalize() throws Throwable {
        super.finalize();
        if (showCleanerSubscription.isDisposed()) {
            showCleanerSubscription.dispose();
        }
    }
}
